import multiprocessing

import numpy
import requests
import ConnectMySql

conn, cursor = ConnectMySql.openConn()

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41",
    "Accept": "application/json, text/plain, */*",
    "Accept-Encoding": "gzip, deflate",
    "Cookie": "Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1676604966; Hm_lpvt_cdb524f42f0ce19b169a8071123a4797=1676604966; _ga=GA1.2.238864722.1676604966; _gid=GA1.2.1591269391.1676604966; kw_token=VW7EK6JAAX",
    "csrf": "VW7EK6JAAX",
    "Referer": "http://www.kuwo.cn/search/list?key=%E5%91%A8%E6%9D%B0%E4%BC%A6",
}


def get_singer_musics(singer_name: str):
    resp = requests.get(
        f'http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key={singer_name}&pn=1&rn=100&httpsStatus=1&reqId=0b5860c0-ae88-11ed-9c21-1d99f9c39310',
        headers=headers)
    list_ = resp.json()['data']['list']
    for m in list_:
        musicrid_ = m['musicrid']
        name = m['name']
        artistid = m['artistid']
        artist = m['artist']
        score = m['score100']
        album = m['album']
        albumid = m['albumid']
        pic = m['pic']

        try:
            cursor.execute(
                "insert into music(musicRid,songName,artist,artistId,album,albumId,score) VALUES (%s,%s,%s,%s,%s,%s,%s)",
                (musicrid_[6:], name, artist, artistid, album, albumid, score))
            conn.commit()
        except Exception as e:
            print(e)
            pass


if __name__ == '__main__':
    pool = multiprocessing.Pool()

    cursor.execute("select sname from singer")
    singerArray = cursor.fetchall()
    singerArray = numpy.array(singerArray)

    for singer in singerArray:
        # get_singer_musics("蔡依林")
        pool.apply_async(get_singer_musics, args=(singer[0],))

    pool.close()
    pool.join()

    ConnectMySql.closeConn(conn, cursor)
